import datetime
import random

from flask import current_app, jsonify
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from info import create_app, db, models
from info.models import User
from info.utils.response_code import RET

app = create_app('develop')

manager = Manager(app)
Migrate(app, db)
manager.add_command('db', MigrateCommand)


#  添加管理员用户，使用装饰器
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def creat_super_user(username, password):
    #  创建管理员用户
    if not all([username, password]):
        print('参数不足')
        return

    admin = User()
    #  设置管理员属性
    admin.mobile = username
    admin.nick_name = username
    admin.password = password
    admin.is_admin = True

    #  提交到数据库
    try:
        db.session.add(admin)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='提交失败')

    return 'ok'


#  添加测试用户
@manager.option('-n', '--name', dest='name')
def add_test_users(name):
    user_list = []
    for num in range(0, 1000):
        #  创建用户对象
        user = User()
        #  设置用户属性
        user.mobile = '132%08d' % num
        user.nick_name = '132%08d' % num
        user.password_hash = 'pbkdf2:sha256:50000$LesTJLTb$931f5d9732fad84952ca6f75b5dd6ae0511441f96a3dc3a4913bb3e419c28861'
        user.last_login = datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 2678440))

        user_list.append(user)
        print(user_list)
        print(num)

    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

        return '添加成功'


if __name__ == '__main__':
    manager.run()
